package com.xyy.saas.payment.adpater.yop;

import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.util.JSONUtils;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.service.mer.MerClient;
import com.yeepay.yop.sdk.service.mer.MerClientBuilder;
import com.yeepay.yop.sdk.service.mer.model.RegisterContributeMerchantV2ContributeMerchantNetInRespDtoResult;
import com.yeepay.yop.sdk.service.mer.request.*;
import com.yeepay.yop.sdk.service.mer.response.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class YopCreateMerchant {
    // 该Client线程安全，请使用单例模式，多次请求共用
    private final MerClient api = MerClientBuilder.builder().build();

    /**
    * 特约商户入网(企业/个体)
    */
    public RegisterContributeMerchantV2ContributeMerchantNetInRespDtoResult createMerchant(RegisterContributeMerchantV2Request param)
            throws PaymentException
    {
        log.info("YopCreateMerchant#createMerchant param:{}", JSONUtils.toJSON(param));

        try {
            RegisterContributeMerchantV2Response response = api.registerContributeMerchantV2(param);
            log.info("YopCreateMerchant#createMerchant request:{} response:{}", JSONUtils.toJSON(param), JSONUtils.toJSON(response));
            RegisterContributeMerchantV2ContributeMerchantNetInRespDtoResult result = response.getResult();

            if(!Constants.YOP_CREATE_ACCOUNT_SUCCESS_CODE.equals(result.getReturnCode())) {
                throw new PaymentException(result.getReturnCode(), result.getReturnMsg());
            }

            return result;
        }
        catch(Exception ex) {
            log.error("YopCreateMerchant#createMerchant error, param=" + JSONUtils.toJSON(param) + ", errorMsg=" + ex.getMessage() ,ex);

            if(ex instanceof PaymentException) {
                throw ex;
            }
            else if(ex instanceof YopClientException) {
                throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR.getCode(), ex.getMessage());
            }

            throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR);
        }
    }
}